<template>
    <van-nav-bar title="出库详情" left-arrow @click-left="handleLeft">
    </van-nav-bar>
    <div class="warehousingRecordDetails">
        <van-overlay :show="overlayShow">
            <van-loading color="#1989fa">加载中...</van-loading>
        </van-overlay>
        <div class="warehousingRecordDetails_header" :show="!overlayShow" ref="warehousingRecordDetails_header">
            <div class="conent_pre_content_div" v-if="details.cancelStatus == 1">
                <div class="div_half div_halfuser">
                    <div class="label red">{{ details.cancelUserName }}：</div>
                    <div class="value red">{{ details.outTime }}</div>
                </div>
                <div class="div_halfs div_halfusers">
                    <div class="canceled">已作废</div>
                </div>
            </div>
            <div class="conent_pre_content_div">
                <div class="div_all">
                    <div class="label">出库时间：</div>
                    <div class="value">{{ details.outTime }}</div>
                </div>
            </div>
            <div class="conent_pre_content_div">
                <div class="div_half">
                    <div class="label">出库人：</div>
                    <div class="value">{{ details.outUserName }}</div>
                </div>
                <div class="div_halfs">
                    <div class="label">出库类型：</div>
                    <div class="value">{{ details.outTypeName }}</div>
                </div>
            </div>
            <div class="conent_pre_content_div conent_pre_content_divs">
                <div class="div_all">
                    <div class="label">出库去向：</div>
                    <div class="value">{{ details.coreName }}</div>
                </div>
            </div>
            <div class="conent_pre_content_div conent_pre_content_divs">
                <div class="img_div" v-if="details.overDay == 0">
                    <van-image :src="daoqi" class="img"></van-image>
                    <div class="colors">{{ details.cycleTime }}</div>
                </div>
                <div class="img_div" v-else>
                    <van-image :src="chaoqi" class="img"></van-image>
                    <div class="colorsRed">{{ details.cycleTime }}</div>
                </div>
            </div>
            <div class="conent_pre_content_div conent_pre_content_divs">
                <div class="div_all">
                    <div class="label">留存照片：</div>
                    <div class="value" v-if="details.cancelStatus !== 1">
                        <div :class="modifyButton ? 'editButton' : 'saveButton'" @click="editClick">{{ modifyButton
                            ?
                            '修改' : '保存' }}</div>
                    </div>
                    <div class="pic_all">
                        <UpLoadDom :arr="outImageList || []" @deleteClick="deleteImg"
                            @postImageClick="postImage('outImage')" :maxCount="modifyButton ? 0 : 5"
                            :look="modifyButton" />
                    </div>
                </div>
            </div>
        </div>
        <van-divider :show="!overlayShow">
            商品详单
        </van-divider>
        <div class="warehousingRecordDetails_content" :show="!overlayShow" :style="computedheight">
            <div class="conent_pre" v-for="(item, index) in list" :key="index" @click="detailsClick(item.productId)"
                :style="{ 'marginTop': index == 0 ? '0' : '2.666667vw' }">
                <div class="conent_pre_header">
                    <div class="conent_pre_img">
                        <van-image :src="item.productImage + '?x-oss-process=image/resize,w_300'"
                            v-if="item.productImage" @click.stop="enlargeImage(item.productImage)"></van-image>
                        <van-image :src="errImg" v-else></van-image>
                        <div class="liveStreamingMechanisms" v-if="item.hmMechanismsList[1]?.cooperationMode">
                            多机制</div>
                    </div>
                    <div class="conent_pre_des">
                        <div class="contnt_title">
                            <div class="contnt_styleName">
                                {{ item.styleName }}
                            </div>
                        </div>
                        <div class="contnt_mechanism">
                            {{ item.sellingPoints }}
                        </div>
                        <div class="contnt_bottom">
                            <div class="price">￥ {{ item.hmMechanismsList[0]?.price ||
                                item.hmMechanismsList[0]?.costPrice }}</div>
                            <div class="commission" v-if="item.hmMechanismsList[0]?.commission">佣 {{
                                (item.hmMechanismsList[0]?.commission || 0) + "%" }}
                            </div>
                            <div class="coreName">{{ item.coreName }}</div>
                        </div>
                    </div>
                </div>
                <div class="product_detail_title--content">
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">机制：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.hmMechanismsList[0]?.liveStreamingMechanism }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">规格/材质：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.specs }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">出库数量：</div>
                        <div class="product_detail_title-content-info-content colors">
                            {{ item.outNum }}件
                        </div>
                    </div>

                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">当前库存：</div>
                        <div class="product_detail_title-content-info-content colors">
                            {{ item.stockAvailable }}件
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">库存编码：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.stockCode }}
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <div class="warehousingRecordDetails_footer" v-if="details.cancelStatus !== 1" ref="warehousingRecordDetails_footer">
            <div class="footer_button" @click="cancellation">作废</div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { selectOutStockById, cancelStockOut, updateOutStockAppList } from '@/api/productHome/index'
import { getEnvValue } from "@/utils/index";
import { showImagePreview, showConfirmDialog, showSuccessToast } from 'vant';
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { handleImageUpdate } from '@/utils/handleImageUpdate';
import UpLoadDom from '@/components/isImgPdf/upLoadDom.vue'
const store = loginStore();
const { token } = storeToRefs(store);
const route = useRoute()
const router = useRouter()
const errImg = new URL("@/assets/home/error.png", import.meta.url).href;
const daoqi = new URL("@/assets/productHome/icon_daoqi.png", import.meta.url).href
const chaoqi = new URL("@/assets/productHome/icon_chaoqi.png", import.meta.url).href
// 设置loading
const overlayShow = ref(true)
const outImageList = ref([])

/** 出库单 */
const details: any = computed(() => {
    return JSON.parse(route.query.details as any)
})
/** 修改按钮 */
const modifyButton = ref(true)

// 列表
const list = ref<any[]>([]);
const warehousingRecordDetails_header = ref()
const headerHeight = ref(0);
const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries) {
        headerHeight.value = entry.contentRect.height;
    }
});
onMounted(() => {
    if (warehousingRecordDetails_header.value) {
        resizeObserver.observe(warehousingRecordDetails_header.value);
    }
});
onUnmounted(() => {
    resizeObserver.disconnect();
});
/** 计算高度 */
const computedheight = computed(() => {
    const height = headerHeight.value;
    // 当前分辨率下盒子转化的vw高度
    const heightinner =  height / window.innerWidth * 100
    if (details.value.cancelStatus !== 1) {
        const totalHeight = 30 + 32 + 60;
        const heighs = totalHeight / 375 * 100;
        // 24px是van-divider自定义样式高度
        // heighs是warehousingRecordDetails_header的padding + van-divider的padding + warehousingRecordDetails_footer的高度
        // heightinner是warehousingRecordDetails_header去除padding的高度
        return { 'height': `calc(100% - ${heighs}vw - ${heightinner}vw - 24px)` };
    } else {
        const totalHeight = 30 + 32;
        const heighs = totalHeight / 375 * 100;
        return { 'height': `calc(100% - ${heighs}vw - ${heightinner}vw - 24px)` };
    }
})
/** 回退 */
const handleLeft = () => {
    // 修改状态下
    if (!modifyButton.value) {
        showConfirmDialog({
            message:
                '您有信息未保存，确认离开？',
        })
            .then(() => {
                router.back()
            })
            .catch(() => {
                // on cancel
            });
    } else {
        router.back()
    }
}
/** 多图片并发请求更改 */
const fetchImagesSequentially = async (real_src, productImageList) => {
    for (const item of real_src) {
        productImageList.push({
            url: item
        });
    }
};
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
/** 修改提交 */
const editClick = async () => {
    // 保存
    if (!modifyButton.value) {
        const outImage = getPicByfullPath(outImageList.value)
        await updateOutStockAppList({ id: details.value.id, outImage: outImage })
        showSuccessToast({ type: 'success', message: '保存成功' });
    }
    modifyButton.value = !modifyButton.value
}
/** 查询商品列表 */
const getList = async () => {
    const res = await selectOutStockById({ outId: details.value.id });
    for (let index = 0; index < res.rows.length; index++) {
        if (res.rows[index].productImage) {
            const real_src = res.rows[index].productImage.split(",");
            res.rows[index].productImage = getEnvValue("VITE_APP_PIC_URL") + real_src[0]
        }
    }
    fetchImagesSequentially(details.value.outImage || [], outImageList.value);
    list.value = res.rows
    overlayShow.value = false
};
getList()


/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
/** 跳转详情 */
const detailsClick = (id: string) => {
    router.push(`/productHomeDetail/${id}`)
}
// 作废
const cancellation = () => {
    showConfirmDialog({
        message:
            '确认作废后，该出库单视为无效，是否继续？',
    }).then(async () => {
        await cancelStockOut({ outId: details.value.id, businessList: list.value })
        showSuccessToast('作废成功')
        router.go(-1)
    });
}
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        outImage: outImageList.value,
    };

    const maxCounts = {
        outImage: 5,
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);
}
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
}
const postImage = (name: string) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: 'img',
            count: 5,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e'
            }
        }
    })
}
</script>
<style lang="less" scoped>
:deep(.van-overlay) {
    display: flex;
    align-items: center;
    justify-content: center;
}

.warehousingRecordDetails {
    width: 100%;
    height: calc(100vh - 90px);
    background-color: #F6FAFF;
    box-sizing: border-box;
    padding-top: 10px;
    overflow: auto;

    .warehousingRecordDetails_header {
        width: 100%;
        background: #FFFFFF;
        display: flex;
        flex-wrap: wrap;
        box-sizing: border-box;
        padding: 15px;

        .conent_pre_content_divs {
            margin-bottom: 0 !important;
        }

        .conent_pre_content_div {
            width: 100%;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .img_div {
                display: flex;
                align-items: center;
            }

            .img {
                width: 14px;
                height: 14px;
                margin-top: 10px;
            }

            .colors {
                font-weight: 400;
                font-size: 12px;
                color: #19D11B;
                margin-top: 10px;
                margin-left: 10px;
            }

            .colorsRed {
                font-weight: 400;
                font-size: 12px;
                color: #FC2540;
                margin-top: 10px;
                margin-left: 10px;
            }

            .label {
                font-weight: 400;
                font-size: 14px;
                color: #1A1B1C;
            }

            .value {
                font-weight: 400;
                font-size: 14px;
                color: #B8BECA;

                .van-image {
                    width: 70px;
                    height: 70px;
                }

                .editButton {
                    width: 58px;
                    height: 24px;
                    border-radius: 5px;
                    border: 1px solid #0094FF;
                    text-align: center;
                    line-height: 24px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #0094FF;
                }

                .saveButton {
                    width: 58px;
                    height: 24px;
                    border-radius: 5px;
                    border: 1px solid #0094FF;
                    text-align: center;
                    line-height: 24px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #0094FF;
                }
            }

            .div_all {
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: wrap;

                .label {
                    width: 90px;
                }

                .pic_all {
                    margin-top: 10px;
                }

                .value {
                    display: flex;
                    width: calc(100% - 90px);
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    flex-wrap: wrap;

                    .value_pic {
                        width: calc(100% / 3);
                    }

                    .value_pic_hang {
                        width: 100%;
                        display: flex;
                    }
                }
            }

            .red {
                color: #FC2540;
            }

            .div_half {
                width: 50%;
                display: flex;
                align-items: center;
            }

            .div_halfuser {
                width: 80%;
            }
            .div_halfusers{
                width: 20% !important;
            }

            .div_halfs {
                width: 50%;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                .canceled {
                    font-size: 14px;
                    color: #B8BECA;
                    background-color: #ECECEC;
                    width: 55px;
                    text-align: center;
                    line-height: 24px;
                    border-radius: 3px;
                }
            }
        }
    }

    .van-divider {
        color: #1A1B1C;
        border-color: #ECECEC;
        padding: 0 15px;
        margin: 16px 0 !important;
        font-weight: 600;
        font-size: 18px;
        color: #1A1B1C;
    }

    .warehousingRecordDetails_content {
        width: 100%;
        overflow: auto;
    }

    .conent_pre {
        width: 100%;
        box-sizing: border-box;
        background-color: #fff;
        box-sizing: border-box;
        padding: 15px;

        .conent_pre_header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .conent_pre_img {
                width: 90px;
                height: 90px;
                position: relative;

                .liveStreamingMechanisms {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 50px;
                    height: 20px;
                    background: #0094FF;
                    border-radius: 2px 0px 2px 0px;
                    font-weight: 400;
                    font-size: 12px;
                    color: #FFFFFF;
                    text-align: center;
                    line-height: 20px;
                }

                .van-image {
                    width: 90px;
                    height: 90px;

                    :deep(.van-image__img) {
                        border-radius: 5px !important;
                    }
                }
            }

            .conent_pre_des {
                width: calc(100% - 90px);
                height: 90px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: wrap;
                padding-left: 10px;
                align-content: space-around;

                .contnt_title {
                    width: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .contnt_styleName {
                        font-weight: 400;
                        font-size: 14px;
                        color: #1A1B1C;
                        width: 150px;
                        height: 20px;
                        white-space: nowrap;
                        /* 确保文本在一行内显示 */
                        overflow: hidden;
                        /* 隐藏溢出的内容 */
                        text-overflow: ellipsis;
                    }

                    .contnt_status {
                        width: 67px;
                        height: 26px;
                        background: #E7FDEE;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #19D11B;
                        text-align: center;
                        line-height: 26px;
                    }

                }

                .contnt_mechanism {
                    width: 100%;
                    font-weight: 400;
                    font-size: 12px;
                    color: #B8BECA;
                    white-space: nowrap;
                    /* 确保文本在一行内显示 */
                    overflow: hidden;
                    /* 隐藏溢出的内容 */
                    text-overflow: ellipsis;
                }

                .contnt_bottom {
                    width: 100%;
                    height: 20px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .price {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .commission {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .coreName {
                        font-weight: 400;
                        font-size: 12px;
                        color: #0094FF;
                    }
                }
            }
        }

        .product_detail_title-content-info {
            margin-top: 20px;
            display: flex;

            .product_detail_title-content-info-name {
                font-weight: 400;
                font-size: 14px;
                color: #1a1b1c;
                line-height: 14px;
                width: 90px;
            }

            .colors {
                color: #0094FF !important;
            }

            .product_detail_title-content-info-content {
                font-weight: 400;
                font-size: 14px;
                color: #b8beca;
                line-height: 14px;
                margin-left: auto;
                width: calc(100% - 75px);
                display: flex;
                align-items: center;
                justify-content: flex-end;
                word-break: break-all;

                .colors_div {
                    display: flex;
                    align-items: center;

                    .img {
                        width: 14px;
                        height: 14px;
                    }

                    .colors {
                        font-weight: 400;
                        font-size: 12px;
                        color: #FC2540 !important;
                        margin-left: 10px;
                        margin-right: 10px;
                    }
                }
            }
        }
    }

    .warehousingRecordDetails_footer {
        width: 100%;
        padding: 15px;
        background: #fff;
        box-sizing: border-box;

        .footer_button {
            width: 100%;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #0094FF;
            color: #fff;
            font-weight: 900;
            border-radius: 15px;
        }
    }
}
</style>